<?php

class DepartmentController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_department');
        $this->session_search_key = 'controller_department';
        $this->session_search_name = 'search_label';
        
        if ($this->_getParam('dep_id') && $this->_getParam('dep_id') != "") {
            $dep_id = $this->_getParam('dep_id');
            $departmentModel = new Model_Department();
            $departmentdata = $departmentModel->fetchEntryByViewId($dep_id);
            if($this->USER->role != 'ADMIN'){
                if($departmentdata['com_id'] != $this->USER->company_id){
                    $this->_helper->redirector('list', 'department', '');
                }
            }
        }
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'department', '');
    }

    public function viewAction() {
        if ($this->_getParam('dep_id') && $this->_getParam('dep_id') != "") {
            $dep_id = $this->_getParam('dep_id');
        } else {
            $this->_helper->redirector('list', 'department', '');
        }
        $departmentModel = new Model_Department();
        $departmentdata = $departmentModel->fetchEntryByViewId($dep_id);
        $updated_id = $departmentdata['lgn_id'];
        $login_type = $departmentdata['lgn_type'];

        /*         * get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        $this->view->admindata = $user_name;
        $this->view->departmentdata = $departmentdata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "1=1 ";
        $searchtype = "";
        $orderField = 'dep_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }


        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }
        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }
        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }
            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "dep_name LIKE '%$searchtype%' OR site_name LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            if ($searchtype != '') {
                $where = "dep_name LIKE '%$searchtype%' OR site_name LIKE '%$searchtype%'  ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        }

        if ($this->USER->roletype == 'Contractor' || $this->USER->roletype == 'SuperContractor' ||
                $this->USER->roletype == 'Customer' || $this->USER->roletype == 'SuperCustomer') {
            $where .=' ) AND (site.com_id=' . $this->USER->company_id;
        } else {
            $where .='';
        }


        if ($this->_getParam('site_id') && $this->_getParam('site_id') != "") {
            $where .= ")AND (department.site_id = '" . $this->_getParam('site_id') . "'";
        }


        $departmentModel = new Model_Department();
        $departmentsData = $departmentModel->fetchDepartment($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($departmentModel->getDepartmentCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'department', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->departmentsData = $departmentsData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $departmentModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Department Model 
        $departmentModel = new Model_Department();
        if ($this->_getParam('dep_id') && $this->_getParam('dep_id') != "") {
            $department_id = $this->_getParam('dep_id');
            $departmentModel->deleteDepartment($department_id);

            $this->addSuccessMessage($this->ZFTRANSLATE->translate("dep_delete_success"));
            $this->_helper->redirector('list', 'department', '');
        } else {
            $departmentModel->deleteDepartment($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("dep_delete_success"));
            $this->_helper->redirector('list', 'department', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $departmentData = Array();
        $this->view->mode = "Add";

        //Load login Model
        $loginModel = new Model_Login();

        //Load Department Model
        $departmentModel = new Model_Department();

        //Load Department Form
        $departmentForm = new Form_DepartmentForm();


        $imageName = "";



        //Load the site array for the select box in form 
        $siteArray = $departmentModel->getsiteArray();
        $departmentForm->site_id->addMultiOptions($siteArray);


        /* //Load the building array for the select box in form 
          $buildingArray = $departmentModel->getbuildingArray();
          $departmentForm->build_id->addMultiOptions($buildingArray);
         */

        //Load the status array for the select box in form 
        $statusArray = $departmentModel->getStatusArray();
        $departmentForm->dep_status->addMultiOptions($statusArray);

        //Check for the department Parameter
        $departmentData['dep_id'] = $this->_request->getParam('dep_id');
        $dep_id = (!empty($departmentData['dep_id'])) ? $departmentData['dep_id'] : null;

        if (!empty($dep_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $departmentModel->fetchEntryById($dep_id);
        }
        //Populate form 
        $this->view->form = $departmentForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$departmentForm->isValid($postedData)) {
                $errorMessage = $departmentForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $DepartmentCount = $departmentModel->getDepartmentCount('');
                        $departmentData['dep_createddate'] = date("Y-m-d H:i:s");
                    }

                    /*                     * authentication login id */
                    $defaultSession = new Zend_Session_Namespace(Zend_Registry::get('sessionName'));
                    $defaultSessionVal = $defaultSession->getIterator();
                    $updated_userid = $defaultSessionVal['storage']->lgn_id;

                    //Department save
                    $departmentData['updated_lgn_id'] = $updated_userid;
                    $departmentData['dep_id'] = $dep_id;
                    $departmentData['site_id'] = $postedData['site_id'];
                    $departmentData['dep_name'] = $postedData['dep_name'];
                    $departmentData['dep_comment'] = $postedData['dep_comment'];
                    $departmentData['dep_status'] = $postedData['dep_status'];
                    $departmentData['dep_updateddate'] = date("Y-m-d H:i:s");

                    $departmentModel->save($departmentData, 'dep_id');

                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("dep_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("dep_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'department', '');
                }
            }
        }
        $this->view->mode = $this->view->mode;
        $this->view->buildid = $dep_id;
        $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $departmentForm;
    }

}

?>
